<?php  

/**
 * Class for Database record validation
 * 
 */  
abstract class Kernel_Validator_Db_Abstract extends Kernel_Validator_Abstract    
{   
    /**
     * Error constants
     */ 
    const NO_RECORD_FOUND = 'NO_RECORD_FOUND';  
    const RECORD_FOUND    = 'RECORD_FOUND';  
 
    /**
     * @var string
     */    
    public $table = '';    
    
    /**
     * @var string
     */    
    public $field = '';    
       
    /**
     * @var mixed
     */   
    public $exclude = null;   
     
    /**
     * Run query and returns matches, or null if no matches are found.
     *
     * @param  String $value
     * @return integer
     */ 
    protected function _query($value) 
    {
        $query = sprintf('
            SELECT
                   COUNT(*)
              FROM 
                   `%s` 
             WHERE 
                   `%s` = "%s"
        ', $this->table, $this->field, database::escape($value));
        if (is_array($this->exclude)) {
            foreach ($this->exclude as $field => $value) {
                $query .= sprintf(' AND `%s` != "%s"', $field, database::escape($value));
            }
        }
        
        return database::fetchOne($query);
    } 
}
